<template>
	<el-space class="go-mt-0" style="margin-right: -8px">
		<el-popover :width="300" trigger="hover" v-if="$store.chart.pageId">
			<template #reference> <el-button icon="Clock"> 历史 </el-button></template>
			<my-table
				row-class-name="pointer"
				:data="versionList"
				:columns="[
					{
						label: '用户',
						prop: 'createBy',
						align: 'center',
						width: 80
					},
					{
						label: '时间',
						prop: 'createTime',
						align: 'center',
						width: 180
					}
				]"
				@row-click="(row) => versionFn(row)"
				max-height="200"
			>
				<template #empty> 暂无数据 </template>
			</my-table>
		</el-popover>
		<el-divider direction="vertical" />
		<el-button v-for="item in btnList" :key="item.title" :type="item.type" :icon="item.icon" @click="item.fnHandle">
			{{ item.title }}
		</el-button>
	</el-space>
</template>

<script setup>
import { editCatalog } from '@a/website';
import { JSONStringify, JSONParse } from '@u';
import { pageHistory, pageHistoryInfo } from '@a/website';

const btnList = [
	{
		title: '保存',
		icon: 'Finished',
		fnHandle: saveHandle
	},
	{
		title: '预览',
		icon: 'View',
		fnHandle: previewHandle
	}
];

// 历史版本
const versionList = ref([]);
function pageHistoryFn() {
	pageHistory({ id: $store.chart.pageId }).then((res) => {
		versionList.value = res.data.reverse();
	});
}
watch(
	() => $store.chart.pageId,
	(val) => {
		if (val) pageHistoryFn();
	}
);

function versionFn(row) {
	pageHistoryInfo({ id: row.id }).then((res) => {
		if (res?.data?.jsonContent) {
			$store.chart.editCanvasConfig = JSONParse(res.data.jsonContent).editCanvasConfig;
			$store.chart.componentList = JSONParse(res.data.jsonContent).componentList;
		}
	});
}
// 保存
function saveHandle() {
	editCatalog({ id: $store.chart.pageId, type: 'Y', jsonContent: JSONStringify($store.chart.getStorageInfo) }).then(
		() => {
			msgSuccess('保存成功!');
			pageHistoryFn();
		}
	);
}
// 预览
function previewHandle() {
	const { href } = $router.resolve({
		name: 'ChartPreview',
		params: {
			pageId: $store.chart.pageId
		}
	});
	window.open(href, '_blank');
}
</script>
